package com.lun.swordtowardoffer2.c11;

public class MinEatingSpeed {
	
	public int minEatingSpeed(int[] piles, int H) {
		int max = Integer.MIN_VALUE;
		
		for(int pile : piles) {
			max = Math.max(max, pile);
		}
		
		int left = 1, right = max;
		
		while(left <= right) {
			int mid = left + (right - left) / 2;
			int total = getTotalHours(piles, mid);
			
			if(total <= H) {
				if(mid == 1 || getTotalHours(piles, mid - 1) > H) {
					return mid;
				}
				right = mid - 1;
			}else {
				left = mid + 1;
			}
		}
		
		return 0;
	}
	
	private int getTotalHours(int[] piles, int speed) {
		int hours = 0;
		
		for(int pile : piles) {
			//右侧式子尽可能向上取整，-1能规避（pile/speed）是整数情况
			hours += (pile + speed - 1) / speed;
		}
		
		return hours;
	}
	
}
